<template>
  <div class="operation-logs-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-select
              v-model="operationType"
              placeholder="操作类型"
              clearable
              @change="handleSearch"
              style="width: 150px"
            >
              <el-option label="登录" value="LOGIN" />
              <el-option label="新增" value="CREATE" />
              <el-option label="修改" value="UPDATE" />
              <el-option label="删除" value="DELETE" />
              <el-option label="查询" value="QUERY" />
              <el-option label="导出" value="EXPORT" />
              <el-option label="导入" value="IMPORT" />
            </el-select>
            
            <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleSearch"
              style="width: 350px"
            />
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          
          <el-button
            type="danger"
            :icon="Delete"
            @click="handleCleanLogs"
            v-if="userStore.isAdmin"
          >
            清理日志
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="logs"
        border
        style="width: 100%"
      >
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="operationType" label="操作类型">
          <template #default="{ row }">
            <el-tag :type="getOperationTypeTag(row.operationType)">
              {{ getOperationTypeLabel(row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationDesc" label="操作内容" show-overflow-tooltip />
        <el-table-column prop="operationIp" label="IP地址" width="120" />
        <el-table-column prop="operationTime" label="操作时间" width="180" />
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 清理日志对话框 -->
    <el-dialog
      v-model="cleanDialogVisible"
      title="清理日志"
      width="400px"
    >
      <el-form
        ref="cleanFormRef"
        :model="cleanForm"
        :rules="cleanRules"
        label-width="100px"
      >
        <el-form-item label="清理时间" prop="beforeTime">
          <el-date-picker
            v-model="cleanForm.beforeTime"
            type="datetime"
            placeholder="选择时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleCleanSubmit" :loading="submitting">
            确定清理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Search } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const cleanDialogVisible = ref(false)
const cleanFormRef = ref(null)
const searchQuery = ref('')
const operationType = ref('')
const timeRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const logs = ref([])

const cleanForm = reactive({
  beforeTime: ''
})

const cleanRules = {
  beforeTime: [
    { required: true, message: '请选择清理时间', trigger: 'change' }
  ]
}

const getOperationTypeLabel = (type) => {
  const typeMap = {
    'LOGIN': '登录',
    'CREATE': '新增',
    'UPDATE': '修改',
    'DELETE': '删除',
    'QUERY': '查询',
    'EXPORT': '导出',
    'IMPORT': '导入'
  }
  return typeMap[type] || type
}

const getOperationTypeTag = (type) => {
  const tagMap = {
    'LOGIN': 'info',
    'CREATE': 'success',
    'UPDATE': 'warning',
    'DELETE': 'danger',
    'QUERY': '',
    'EXPORT': 'success',
    'IMPORT': 'warning'
  }
  return tagMap[type] || ''
}

const fetchLogs = async () => {
  try {
    loading.value = true
    const res = await request.get('api/operation-logs/page', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        username: searchQuery.value,
        operationType: operationType.value,
        startTime: timeRange.value?.[0],
        endTime: timeRange.value?.[1]
      }
    })
    if (res.code === 200) {
      logs.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取操作日志失败')
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
    ElMessage.error('获取操作日志失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchLogs()
}

const resetSearch = () => {
  searchQuery.value = ''
  operationType.value = ''
  timeRange.value = []
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchLogs()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchLogs()
}

const handleCleanLogs = () => {
  cleanForm.beforeTime = ''
  cleanDialogVisible.value = true
}

const handleCleanSubmit = async () => {
  if (!cleanFormRef.value) return
  
  try {
    await cleanFormRef.value.validate()
    submitting.value = true
    
    await request.delete('api/operation-logs/clean', {
      params: {
        time: cleanForm.beforeTime
      }
    })
    
    ElMessage.success('清理成功')
    cleanDialogVisible.value = false
    fetchLogs()
  } catch (error) {
    console.error('清理日志失败:', error)
    ElMessage.error('清理日志失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchLogs()
})
</script>

<style scoped>
.operation-logs-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 